package javax.per.toolkit.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.per.toolkit.tools.msg.Msg;

/**
 *<br/><br/>
 *<strong>Test code</strong><br/>
 *	public static void main(String[] args) throws IOException{<br/>
 *		new ChangeFileEncoding().setFile("filepath").setFile("filepath").changeEncoding("encoding1","encoding2");<br/>
 *	}<br/>
 *
 * @author Think
 *
 */

public class ChangeFileEncoding {
	
	File file=null;
	
	/**
	 * Set file
	 * @param file file to be converted
	 * @return an instance of ChangeFileEncoding
	 */
	public ChangeFileEncoding setFile(File file) {
		this.file = file;
		return this;
	}
	
	/**
	 * 
	 * @param filePath the path of the file to be converted
	 * @return an instance of ChangeFileEncoding
	 */
	public ChangeFileEncoding setFile(String filePath) {
		this.file = new File(filePath);
		return this;
	}
	
	/**
	 * Check for error
	 */
	public void checkFile(){
		if(file==null||!file.exists())
			throw new Error(Msg.get("FNF"));
	}

	
	/**
	 * Change file's encoding
	 * @param from the currently encoding name of the file
	 * @param to the encoding name want to be converted
	 * @throws IOException
	 */
	public void changeEncoding(String from,String to) throws IOException{
		checkFile();
		convert(from,to);
	}	
	
	
	/**
	 * Change file's encoding,the source file's encoding will be auto checked.
	 * @param to the encoding name want to be converted
	 * @throws IOException
	 */
	public void changeEncoding(String to) throws IOException{
		checkFile();
		String from=DetectEncoding.getEncoding(file);
		convert(from,to);
	}
	
	
	
	protected void convert(String from,String to) throws IOException{
		File fileTmp=File.createTempFile(file.getName(), null);
		InputStream is=new FileInputStream(file);
		InputStreamReader isr=new InputStreamReader(is,from);
		OutputStream os=new FileOutputStream(fileTmp);
		int len=0;
		char[] cs=new char[100];
		byte[] bs=null;
		while((len=isr.read(cs))!=-1){
			String strTmp=new String(cs,0,len);
			bs=strTmp.getBytes(to);
			os.write(bs);
		}
		os.close();
		isr.close();
		is.close();
		String path=file.getAbsolutePath();
		file.delete();
		fileTmp.renameTo(new File(path));
	}
	
	/**
	 * Example for using this class.
	 * @param args command line.
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException{
		new ChangeFileEncoding().setFile("filepath").setFile("filepath").changeEncoding(/*"encoding1", */"encoding2");
	}
	

}
